import React,{useContext, useEffect, useRef, useState} from 'react'
import {MyContext} from '../App'

const TodoItem = ({item}) => {
    const cginputRef = useRef()
    const {cgItemFinish,delItem,cgItem} = useContext(MyContext)
    const [cgiteminfo,setItemInfo] = useState({id:'',content:''})

    useEffect(() => {
      cginputRef.current.focus()
    }, [cgiteminfo])
    

    const cgItemInfo = ({id,content}) => {// 控制修改计划输入框
        setItemInfo({ id,content })
    }

    const cgKeyUp = (e) => { // 修改计划输入框键盘事件
        if(e.keyCode === 13) {
            cgItem(cgiteminfo)
            setItemInfo({id:'',content:''})
        }
        if(e.keyCode === 27) {
            setItemInfo({id:'',content:''})
        }
    }

    return <li className={[item.finish?'completed':'',cgiteminfo.id === item.id ? 'editing':''].join(' ')} key={item.id}>
        <div className="view">
            <input className="toggle" type="checkbox" checked={item.finish} onChange={()=>cgItemFinish(item.id)}/>
            <label onDoubleClick={()=>cgItemInfo(item)}>{item.content}</label>
            <button className="destroy" onClick={()=>delItem(item.id)} />
        </div>
        <input className="edit" value={cgiteminfo.content} onChange={(e)=>setItemInfo({...cgiteminfo,content:e.target.value})} onKeyUp={(e)=>cgKeyUp(e)} ref={cginputRef}/>
    </li>
}

export default TodoItem
